package org.marsdonne.auth.messenger;

import org.marsdonne.auth.EndPointUser;
import org.marsdonne.auth.EndPointUserRepos;
import org.marsdonne.auth.OrganizationStaff;
import org.marsdonne.auth.UnionUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.Optional;

@Component
public class UserListener {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserListener.class);

    @Resource
    private EndPointUserRepos repos;

    @Transactional
    @JmsListener(containerFactory = "authListenerFactory", concurrency = "1-5",
            destination = "${auth.artemis.channels.user.join.organization:channels.user.join.organization}")
    public void bind(OrganizationStaff staff) {
        Optional<EndPointUser> optionalEndPointUser = repos.bind(staff.getUserIdentifier(), staff.getUserRealName(), staff.getUserResidentId(),
                staff.getOrganizationType(), staff.getOrganizationId(), staff.getOrganizationLicenseCode(), staff.getOrganizationName());

        if (!optionalEndPointUser.isPresent()) {
            LOGGER.error("Failed to join the organization[{}], not found user[{}]", staff.getOrganizationLicenseCode(), staff.getUserIdentifier());
        }
    }

    @Transactional
    @JmsListener(containerFactory = "authListenerFactory", concurrency = "1-5",
            destination = "${auth.artemis.channels.user.leave.organization:channels.user.leave.organization}")
    public void unbind(OrganizationStaff staff) {
        Optional<UnionUser> optionalUnionUser = repos.unbind(staff.getUserResidentId(), staff.getOrganizationLicenseCode());
        if (!optionalUnionUser.isPresent()) {
            LOGGER.error("Failed to leave the organization[{}], not found user[{}]", staff.getOrganizationLicenseCode(), staff.getUserIdentifier());
        }
    }
}
